package com.neusoft.elmboot.controller;

import com.neusoft.elmboot.dto.UserDTO;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/persons")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/auth")
    public UserDTO getUserByIdByPass(@RequestBody User user, HttpSession session, HttpServletResponse response) {
        try {
            UserDTO userDTO = userService.getUserByIdByPass(user);
            if (userDTO != null) {
                session.setAttribute("userId", userDTO.getUserId());
                Cookie cookie = new Cookie("token", user.getUserId());
                cookie.setPath("/");
                response.addCookie(cookie);
                return userDTO;
            } else {
                return new ResponseEntity<UserDTO>(HttpStatus.NOT_FOUND).getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @GetMapping("/{userId}")
    public User getUserById(@PathVariable String userId) throws Exception {
        return userService.getUserById(userId);
    }

    @PostMapping
    public int saveUser(@RequestBody User user, HttpServletResponse response) {
        try {
            int result = userService.saveUser(user);
            if (result > 0) {
                Cookie cookie = new Cookie("token", user.getUserId());
                cookie.setPath("/");
                response.addCookie(cookie);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}